package datasource

import (
	"errors"
	"fmt"
	"zhou_gin_api/appLog"
	"zhou_gin_api/config"
	//_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
)

var gormDb *gorm.DB

func NewDbMaster() *gorm.DB {
	dbConfig := config.GetDbConfig()
	appConfig := config.GetAppConfig()

	sourcename := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbConfig.UserName,
		dbConfig.Password,
		dbConfig.Host,
		dbConfig.Port,
		dbConfig.Database,
	)

	var err error
	instance, err := gorm.Open("mysql", sourcename)

	if err != nil {
		log.Fatal("dbhelper.InstanceDbMaster NewEngine error ", err)
	}
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return dbConfig.Prefix + defaultTableName
	}

	if appConfig.Debug {
		instance = instance.Debug()
	}

	return instance
}

func SetInstanceDb(db *gorm.DB) {
	gormDb = db
}

func GetGormDb() *gorm.DB {
	return gormDb
}

//事务处理
func DbTransaction(transactionFunc func(t *gorm.DB) (err error)) (err error) {

	tx := gormDb.Begin()
	defer func() {
		if r := recover(); r != nil {
			appLog.ErrorLog("事务失败", r)
			tx.Rollback()
			err = errors.New("数据异常")
		}
	}()

	if tx.Error != nil {
		tx.Rollback()
		return err
	}

	err = transactionFunc(tx)
	if err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
